#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import stat

class FileDirUitl(object):

    def __init__(self):
        pass

    @staticmethod
    def normalize_path(path):
        '''规范化路径'''

        try:
            char_map = {
                '\b': '/b',
                '\a': '/a',
                '\f': '/f',
                '\r': '/r',
                '\n': '/n',
                '\t': '/t',
                '\v': '/v',
                '\0': '/0',
                '\\': '/'
            }

            for char, map in char_map.items():
                path = path.replace(char, map)
        except Exception as e:
            print('规范话路径出错：%s' % e)
        finally:
            return os.path.abspath(path.strip())


    @staticmethod
    def mkdirs(path):
        '''批量创建目录'''

        try:
            path = FileDirUitl.normalize_path(path)
            if os.path.isdir(path):
                return True

            if os.path.isfile(path):
                print('路径已存在，且指向文件')
                return False

            head, tail = os.path.split(path)
            if tail == '': # head为根目录，形如 / 、D:
                return True

            new_dir_path = ''  # 存放反转后的目录路径
            root = ''  # 存放根目录
            while tail:
                new_dir_path = new_dir_path + tail + '/'
                head, tail = os.path.split(head)
                root = head
            else:
                new_dir_path = os.path.join(root, new_dir_path.rstrip('/'))

                # 批量创建目录
                head, tail = os.path.split(new_dir_path)
                current_path = root
                while tail:
                    current_path = os.path.join(current_path, tail)

                    if not os.path.exists(current_path):
                        os.mkdir(current_path)
                    head, tail = os.path.split(head)
            return True
        except Exception as e:
            print('批量创建目录出错：%s' % e)
            return False

    @staticmethod
    def rm_file_or_dirs(path):
        '''批量删除目录、文件'''


        def remove(path):
            if os.path.isdir(path):
                for name in os.listdir(path):
                    full_path = os.path.join(path, name)
                    remove(full_path)

                os.chmod(path, stat.S_IRWXO+stat.S_IRWXG+stat.S_IRWXU)
                os.rmdir(path)
            else:
                os.chmod(path, stat.S_IRWXO+stat.S_IRWXG+stat.S_IRWXU)
                os.remove(path)
        try:
            path = FileDirUitl.normalize_path(path)
            if not os.path.exists(path):
                return True
            remove(path)
            return True
        except Exception as e:
            print('批量删除目录、文件出错：%s' % e)
            return False
